import { create } from "zustand";
import { BearSlice, createBearSlice, initialBearState } from "./bearSlice";
import { createFishSlice, FishSlice, initialFishState } from "./fishSlice";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";

export type StoreState = BearSlice & FishSlice;

// 重置store
export enum StoreName {
  Fish = "fish",
  Bear = "bear",
}

interface Resetters {
  store: StoreName;
  reset: () => void;
}

const initStateArr = [
  { store: StoreName.Fish, state: initialFishState },
  { store: StoreName.Bear, state: initialBearState },
];
const resetters: Resetters[] = [];

// 重置全部或部分store
export const resetAllSlices = (resetStoreArr?: StoreName[]) => {
  resetters.forEach((resetter) => {
    if (!resetStoreArr) {
      resetter.reset();
      return;
    } else {
      if (resetStoreArr.includes(resetter.store)) {
        resetter.reset();
      }
    }
  });
};

const useZuStore = create<
  StoreState,
  [
    ["zustand/immer", never],
    ["zustand/devtools", never],
    ["zustand/persist", StoreState]
  ]
>(
  immer(
    devtools(
      persist(
        (set, ...a) => {
          initStateArr.forEach((state) => {
            resetters.push({
              store: state.store,
              reset: () => set(state.state),
            });
          });
          return {
            ...createBearSlice(set, ...a),
            ...createFishSlice(set, ...a),
          };
        },
        { name: "zustand-store" }
      )
    )
  )
);

export default useZuStore;
